import {defineStore} from "pinia";
import {ref,computed} from "vue";
import {useUserStore} from "@/stores/userStore.js";
import {delCartAPI, findNewCartListAPI, insertCartAPI} from "@/apis/cart.js";
import {ElMessage} from "element-plus";


export const useCartStore= defineStore('cart',()=>{
    const cartList=ref([])
    const userStore=useUserStore()
    const isLogin = computed(()=>userStore.userInfo.token)


    const updateNewList=async ()=>{
        const res= await findNewCartListAPI()
        cartList.value=res.result
    }

    const addCart = async (goods) => {
        const {skuId,count}=goods
        if (isLogin.value){
            await insertCartAPI({skuId, count})
            ElMessage({message:'添加购物车成功',type:'success'})
            updateNewList()
        }else {
        // 添加购物车操作
        // 已添加过 - count + 1
        // 没有添加过 - 直接push
        // 思路：通过匹配传递过来的商品对象中的skuId能不能在cartList中找到，找到了就是添加过
            const item = cartList.value.find((item) => goods.skuId === item.skuId)
            if (item) {
                // 找到了
                item.count++
            } else {
                // 没找到
                cartList.value.push(goods)
            }
        }
    }
    const delCart = async (skuId) => {
        if (isLogin.value) {
            // 调用接口实现接口购物车中的删除功能
            await delCartAPI([skuId])
            ElMessage({message:'删除商品成功',type:'success'})
            updateNewList()
        } else {
            // 思路：
            // 1. 找到要删除项的下标值 - splice
            // 2. 使用数组的过滤方法 - filter
            const idx = cartList.value.findIndex((item) => skuId === item.skuId)
            cartList.value.splice(idx, 1)
        }
    }

    const clearCart = () =>{
        cartList.value=[]
    }


    // 单选功能
    const singleCheck = (skuId, selected) => {
    console.log(skuId, selected);
    // 通过 skuId 找到要修改的那一项，然后把它的 selected 修改为传过来的 selected
    const item = cartList.value.find((item) => item.skuId === skuId);
    console.log(item);
    // 检查是否找到了对应的 item
    if (item) {
        item.selected = selected;
    } else {
        console.error(`Item with skuId ${skuId} not found.`);
    }
    }

    const allCheck=(selected)=>{
        cartList.value.forEach((item)=>item.selected=selected)
    }



    const allCount = computed(()=>cartList.value.reduce((a,c)=>a+c.count,0))
    const allPrice = computed(()=>cartList.value.reduce((a,c)=>a+c.count*c.price,0))

    const selectedCount= computed(()=>cartList.value.filter(item=>item.selected).reduce((a,c)=>a+c.count,0))
    const selectedPrice= computed(()=>cartList.value.filter(item=>item.selected).reduce((a,c)=>a+c.count*c.price,0))

    const isAll= computed(()=>cartList.value.every((item)=>item.selected))


    return{
        cartList,
        addCart,
        delCart,
        allPrice,
        allCount,
        singleCheck,
        allCheck,
        isAll,
        selectedCount,
        selectedPrice,
        clearCart,
        updateNewList
    }


    },{
    persist:true
})